package com.five.taotao.guide;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.five.taotao.Adapter.ShopCollectAdapter;
import com.five.taotao.Adapter.ShopcarAdapter;
import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import com.five.taotao.entity.Product;
import com.five.taotao.entity.ShoppingCart;
import com.five.taotao.guide_mine.ShopCarActivity;
import com.five.taotao.login.LoginActivity;
import com.five.taotao.order_details.OrderConfirmActivity;
import com.five.taotao.product_details.ProductDetailsActivity;
import com.five.taotao.util.Constants;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShoppingCartFragment extends Fragment {

    @BindView(R.id.lv_shopcar)
    ListView lvShopcar;


    private View v;
    private List<ShoppingCart.ListBean> mData;

    private ListView listView;
    private ShopcarAdapter shopcarAdapter;
    private ShoppingCart.ListBean product;
    private List<ShoppingCart.ListBean> payData;
    private List<ShoppingCart.ListBean> delData;
    private TextView tv_shopcar_editor;
    private boolean editor_flag = false;
    private TextView tv_shopcar_money;
    private TextView tv_shopcar_money_w;
    private TextView tv_shopcar_topay;
    private CheckBox cb_shopcar_allselected;

    private double sum;

    public ShoppingCartFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (v == null) {
            v = inflater.inflate(R.layout.fragment_shopping_cart, container, false);
            ButterKnife.bind(this, v);
            listView = (ListView) v.findViewById(R.id.lv_shopcar);
            mData = new ArrayList<>();
            payData = new ArrayList<>();
            delData = new ArrayList<>();
            shopcarAdapter = new ShopcarAdapter(mData, getActivity());

            tv_shopcar_money = (TextView) v.findViewById(R.id.tv_shopcar_money);//结算总价
            tv_shopcar_money_w = (TextView) v.findViewById(R.id.tv_shopcar_money_w);//“合计：”
            tv_shopcar_editor = (TextView) v.findViewById(R.id.tv_shopcar_editor);//编辑
            tv_shopcar_topay = (TextView) v.findViewById(R.id.tv_shopcar_topay);//支付、删除按钮
            cb_shopcar_allselected = (CheckBox) v.findViewById(R.id.cb_shopcar_allselected);//全选按钮
            shopcarAdapter.setOnShopcarListener(new ShopcarAdapter.ShopcarListener() {
                @Override
                public void select(final ShopcarAdapter.ViewHolder viewHolder, View view, int postion) {
                    product = mData.get(postion);
                    //判断结算栏是否显示
                    for (int i = 0; i < mData.size(); i++) {
                        if (mData.get(i).getIsSelected()) {
                            viewHolder.end.setVisibility(View.VISIBLE);
                        } else {
                            viewHolder.end.setVisibility(View.GONE);
                        }
                    }
                    viewHolder.goods.setTag(postion);
                    viewHolder.goods.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckBox ch = (CheckBox) view;
                            int po = (int) ch.getTag();
                            if (ch.isChecked()) {
                                mData.get(po).setIsSelected(true);
                                viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                                viewHolder.store.setChecked(mData.get(po).getIsSelected());
                                viewHolder.end.setVisibility(View.VISIBLE);
                                //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                                if (editor_flag) {
                                    delData.add(mData.get(po));
                                    tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                                } else {
                                    payData.add(mData.get(po));//将选中的商品加到支付集合中
                                    tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                    //同时更新总费用
                                    double newMoney = sumCost(tv_shopcar_money, po, true);
                                    tv_shopcar_money.setText("￥" + newMoney);

                                }
                            } else {
                                mData.get(po).setIsSelected(false);
                                viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                                viewHolder.store.setChecked(mData.get(po).getIsSelected());
                                viewHolder.end.setVisibility(View.GONE);
                                //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                                if (editor_flag) {
                                    delData.remove(mData.get(po));
                                    tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                                } else {
                                    payData.remove(mData.get(po));//将选中的商品从集合中去除
                                    tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                    double newMoney = sumCost(tv_shopcar_money, po, false);
                                    tv_shopcar_money.setText("￥" + newMoney);
                                }

                            }
                        }
                    });
                    viewHolder.goods.setChecked(product.getIsSelected());
                    viewHolder.store.setChecked(product.getIsSelected());

                    viewHolder.store.setTag(postion);
                    viewHolder.store.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckBox ch = (CheckBox) view;
                            int po = (int) ch.getTag();
                            if (ch.isChecked()) {
                                mData.get(po).setIsSelected(true);
                                viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                                viewHolder.store.setChecked(mData.get(po).getIsSelected());
                                viewHolder.end.setVisibility(View.VISIBLE);
                                //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                                if (editor_flag) {
                                    delData.add(mData.get(po));
                                    tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                                } else {
                                    payData.add(mData.get(po));//将选中的商品加到集合中
                                    tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                    double newMoney = sumCost(tv_shopcar_money, po, true);
                                    tv_shopcar_money.setText("￥" + newMoney);
                                }
                            } else {
                                mData.get(po).setIsSelected(false);
                                viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                                viewHolder.store.setChecked(mData.get(po).getIsSelected());
                                viewHolder.end.setVisibility(View.GONE);
                                //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                                if (editor_flag) {
                                    delData.remove(mData.get(po));
                                    tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                                } else {
                                    payData.remove(mData.get(po));//将选中的商品从集合中去除
                                    tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                    double newMoney = sumCost(tv_shopcar_money, po, false);
                                    tv_shopcar_money.setText("￥" + newMoney);
                                }
                            }
                        }
                    });
                    viewHolder.goods.setChecked(product.getIsSelected());
                    viewHolder.store.setChecked(product.getIsSelected());
                }

                @Override
                public void decGoods(final ShopcarAdapter.ViewHolder viewHolder, View view, int postion) {
                    product = mData.get(postion);

                    viewHolder.dec.setTag(postion);
                    viewHolder.count.setTag(postion);
                    viewHolder.dec.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ImageView im = (ImageView) view;
                            int po = (int) im.getTag();
                            int tmp = mData.get(po).getNum() - 1;
                            if (tmp == 0) {
                                MyApplication.toast.toastShow("购买数量至少为一件");
                                return;
                            }
                            mData.get(po).setNum(mData.get(po).getNum() - 1);
                            viewHolder.count.setText(mData.get(po).getNum() + "");
                            viewHolder.count1.setText("已选" + mData.get(po).getNum() + "件商品,合计：");
                            viewHolder.cost.setText("￥" + mData.get(po).getNum() * mData.get(po).getVipprice());
                            if (mData.get(po).getIsSelected()) {
                                //更新总费用
                                String oldMoney = tv_shopcar_money.getText().toString();//￥120
                                double money = Double.parseDouble(oldMoney.substring(1));
                                money -= mData.get(po).getVipprice();
                                tv_shopcar_money.setText("￥" + money);
                            }
                        }
                    });
                    viewHolder.count.setText(product.getNum() + "");
                    viewHolder.count1.setText("已选" + product.getNum() + "件商品,合计：");
                    viewHolder.cost.setText("￥" + product.getNum() * product.getVipprice());
                }

                @Override
                public void incGoods(final ShopcarAdapter.ViewHolder viewHolder, View view, int postion) {
                    product = mData.get(postion);

                    viewHolder.inc.setTag(postion);
                    viewHolder.count.setTag(postion);
                    viewHolder.inc.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ImageView im = (ImageView) view;
                            int po = (int) im.getTag();
                            mData.get(po).setNum(mData.get(po).getNum() + 1);
                            viewHolder.count.setText(mData.get(po).getNum() + "");
                            viewHolder.count1.setText("已选" + mData.get(po).getNum() + "件商品,合计：");
                            viewHolder.cost.setText("￥" + mData.get(po).getNum() * mData.get(po).getVipprice());
                            if (mData.get(po).getIsSelected()) {
                                //更新总费用
                                String oldMoney = tv_shopcar_money.getText().toString();//￥120
                                double money = Double.parseDouble(oldMoney.substring(1));
                                money += mData.get(po).getVipprice();
                                tv_shopcar_money.setText("￥" + money);
                            }
                        }
                    });
                    viewHolder.count.setText(product.getNum() + "");
                    viewHolder.count1.setText("已选" + product.getNum() + "件商品,合计：");
                    viewHolder.cost.setText("￥" + product.getNum() * product.getVipprice());
                }
            });

            //编辑、完成按钮
            tv_shopcar_editor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (editor_flag) {
                        //更新后台
                        List<Integer> list=new ArrayList<>();
                        for (int i=0;i<delData.size();i++){
                            list.add(delData.get(i).getCarid());
                        }
                        //将购物城表中的数据删除
                        mData.removeAll(delData);
                        delData.clear();
                        shopcarAdapter.notifyDataSetChanged();

                        Gson gson=new Gson();
                        String g=gson.toJson(list);
                        OkHttpUtils
                                .post()
                                .url(Constants.SD_URL)
                                .addParams("carids", g)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {

                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        if(delData.size()!=0){
                                            MyApplication.toast.toastShow("删除成功");
                                        }
                                    }
                                });
                        //更新前台
                        editor_flag = false;
                        tv_shopcar_editor.setText("编辑");
                        tv_shopcar_money.setVisibility(View.VISIBLE);//显示
                        tv_shopcar_money_w.setVisibility(View.VISIBLE);//显示
                        tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                        cb_shopcar_allselected.setChecked(false);


                    } else {
                        editor_flag = true;
                        tv_shopcar_editor.setText("完成");
                        tv_shopcar_money.setVisibility(View.GONE);//隐藏
                        tv_shopcar_money_w.setVisibility(View.GONE);//隐藏
                        //将在支付页面已经选中的数据加到删除集合中
                        for (int i = 0; i < mData.size(); i++) {
                            if (mData.get(i).getIsSelected()) {
                                delData.add(mData.get(i));
                            }
                        }
                        //同时将支付集合中的数据清空
                        payData.clear();
                        tv_shopcar_money.setText("￥0.0");
                        tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                    }
                }
            });

            //支付或者删除

            tv_shopcar_topay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (editor_flag) {//删除
                        //更新后台
                        List<Integer> list=new ArrayList<>();
                        for (int i=0;i<delData.size();i++){
                            list.add(delData.get(i).getCarid());
                        }
                        Gson gson=new Gson();
                        String g=gson.toJson(list);
                        OkHttpUtils
                                .post()
                                .url(Constants.SD_URL)
                                .addParams("carids", g)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        MyApplication.toast.toastShow("网络异常");
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        MyApplication.toast.toastShow("删除成功");
                                    }
                                });
                        //更新界面
                        mData.removeAll(delData);
                        delData.clear();
                        shopcarAdapter.notifyDataSetChanged();
                        tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                        cb_shopcar_allselected.setChecked(false);

                    } else {//支付
                        //跳转到支付界面
                        SharedPreferences sp=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
                        String userid=sp.getString("userId","");
                        if(userid==""){
                            Intent intent=new Intent(getActivity(), LoginActivity.class);
                            startActivity(intent);
                        }else{
                            if(payData.size()==0){
                                MyApplication.toast.toastShow("您还没有选中任何商品");
                            }else{
                                Log.e("支付", payData.size() + "");
                                Intent intent = new Intent(getActivity(), OrderConfirmActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("list", (Serializable) payData);
                                intent.putExtras(bundle);
                                startActivity(intent);
                            }
                        }

                    }
                }
            });
            //全选按钮
            cb_shopcar_allselected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        sum = 0;
                        //将全部元素标记为已选
                        for (int i = 0; i < mData.size(); i++) {
                            mData.get(i).setIsSelected(true);
                            sum += mData.get(i).getVipprice() * mData.get(i).getNum();
                        }
                        shopcarAdapter.notifyDataSetChanged();
                        if (editor_flag) {//全选加入删除集合
                            if (!delData.isEmpty()) {//不是空集合，先清空
                                delData.clear();
                            }
                            delData.addAll(mData);
                            tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                        } else {//全选加入支付集合
                            if (!payData.isEmpty()) {
                                payData.clear();
                            }
                            payData.addAll(mData);
                            tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                        }
                        //同时更新总费用
                        tv_shopcar_money.setText("￥" + sum);
                    } else {//全反选
                        for (int i = 0; i < mData.size(); i++) {
                            mData.get(i).setIsSelected(false);
                        }
                        shopcarAdapter.notifyDataSetChanged();
                        if (editor_flag) {
                            delData.clear();
                            tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                        } else {
                            payData.clear();
                            tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                        }
                        //更新总费用
                        tv_shopcar_money.setText("￥0.0");
                    }
                }
            });
        }
        return v;
    }

    @Override
    public void onStart() {
        mData.clear();
        shopcarAdapter.notifyDataSetChanged();
//        SharedPreferences sp=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
//        String userid=sp.getString("userId","");
        String userid=MyApplication.userId;
        if(userid != ""){
            //后台请求数据
            loadData();
//            listView.getItemAtPosition(2);
            payData.clear();
            sum = 0.0;
            tv_shopcar_money.setText("￥0.0");
            tv_shopcar_topay.setText("去支付(0)");
            listView.setAdapter(shopcarAdapter);
        }else{
            payData.clear();
            delData.clear();
            tv_shopcar_money.setText("￥0.0");
            tv_shopcar_topay.setText("去支付(0)");
        }
        super.onStart();
    }

    /**
     * @param tv_shopcar_money 已经选中商品总费用
     * @param po               选中的位置
     * @return
     */
    private double sumCost(TextView tv_shopcar_money, int po, boolean isselected) {
        String oldMoney = tv_shopcar_money.getText().toString();//￥120
        double money = Double.parseDouble(oldMoney.substring(1));
        double vipprice = mData.get(po).getVipprice();
        int count = mData.get(po).getNum();
        if (isselected) {
            return money + vipprice * count;
        }
        return money - vipprice * count;
    }


    private void loadData() {
        OkHttpUtils
                .post()
                .url(Constants.SC_URL)
                .addParams("id", MyApplication.userId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                       /* Log.i("TAG", response);*/
                        Gson gson = new Gson();
                        ShoppingCart musicWebAlbum = gson.fromJson(response, ShoppingCart.class);
                        List<ShoppingCart.ListBean> items = musicWebAlbum.getList();
                        mData.clear();
                        mData.addAll(items);
                        shopcarAdapter.notifyDataSetChanged();
                    }
                });
    }

}
